<template>
  <div>
    <vol-box :model.sync="model.box1" title="商品预约" :height="460" :width="700" :padding="10">
      <VolForm :loadKey="true" ref="formFieldsreset" :formFields="formFields" :formRules="formRules"></VolForm>
      <el-card class="box-card">
        <div slot="header" class="df clearfix">
          <span>采购商品</span>
          <div class="df">
            <a href="https://api.boss.i-town.cn/api/Small_procure_order/DownLoadOrderTemplate">导入订单信息模板</a>
            <!-- <el-button type="success" size="small" class="ml10" @click="downloadExcel2">下载订单信息模板</el-button> -->
            <div style="width: 120px" v-show="url2">
              <VolUploadFile :url="url2" :upload-after="uploadAfter2" class="ml10"></VolUploadFile>
            </div>
            <el-button type="success" size="small" class="ml10" @click="uploadFun" v-show="!url2">导入订单信息</el-button>
            <el-button type="success" size="small" class="ml10" @click="reservation(1)">预约</el-button>
            <el-button type="success" class="ml10" size="small" @click="reservation(2)">批量预约</el-button>
          </div>
        </div>
        <!--  @selection-change="(e)=>{multipleList = e}" -->
        <el-table class="table" ref="goodsTableref" :data="goodTableData" tooltip-effect="dark" height="250" style="width: 100%" @row-click="rowClickHandle">
          <!-- <el-table-column type="selection" width="45"></el-table-column> -->
          <el-table-column width="45" align="center">
            <template slot-scope="scope">
              <el-radio :label="scope.row.goods_id" v-model="radioId">{{ "" }}</el-radio>
            </template>
          </el-table-column>
          <el-table-column type="index" label="序号"></el-table-column>
          <el-table-column prop="name" label="商品名称" show-overflow-tooltip></el-table-column>
          <el-table-column prop="goodcode" label="编码" show-overflow-tooltip></el-table-column>
          <el-table-column prop="price" label="单价" show-overflow-tooltip></el-table-column>
          <el-table-column prop="time" label="有效期" show-overflow-tooltip></el-table-column>
        </el-table>
      </el-card>
    </vol-box>
    <vol-box :lazy="true" :model.sync="model.box2"  title="手工采购预约" :height="380" :width="800" :padding="10">
      <el-table class="table" ref="goodsTableref2" :data="goodTableData2" tooltip-effect="dark" height="120" style="width: 100%;">
        <el-table-column prop="title" label="商品名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="price" label="商品价格"></el-table-column>
        <el-table-column prop="num" label="商品数量">
          <template slot-scope="scope">
            <el-input-number ref="refNumber" controls-position="right" size="mini" :min="1" v-model="scope.row.num" />
          </template>
        </el-table-column>
        <el-table-column label="商品总价" width="85px">
          <template slot-scope="scope">
            {{ scope.row.num * scope.row.price }}
          </template>
        </el-table-column>
      </el-table>
      <VolForm ref="myform" style="margin-top:10px;" :loadKey="true" :formFileds="formFileds2" :formRules="formRules2"></VolForm>
      <div slot="footer" style="height:30px;">
        <Button type="success" @click="confirmFun(1)">确认预约</Button>
      </div>
    </vol-box>
    <vol-box :lazy="true" :model.sync="model.box3" title="手工采购批量预约" :height="530" :width="1000" :padding="10">
      <el-table class="table" ref="goodsTableref2" :data="goodTableData2" tooltip-effect="dark" height="120" style="width: 100%;">
        <el-table-column prop="title" label="商品名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="price" label="商品价格"></el-table-column>
        <!-- <el-table-column prop="num" label="商品数量">
          <template slot-scope="scope">
            <el-input-number ref="refNumber" controls-position="right" size="mini" :min="1" v-model="scope.row.num"></el-input-number>
          </template>
        </el-table-column> -->
      </el-table>
      <el-card class="box-card">
        <div slot="header" class="df clearfix" style="min-height:85px;padding:0px 20px;">
          <span>人员信息</span>
          <div style="min-height:85px;">
            <el-form ref="ruleFormU" :model="form2" :inline="true" label-width="90px" >
              <div style="height:40px;">
                <el-form-item label="秒数起" required>
                  <el-input-number v-model="form2.minSeconds" :min="1" :max="59" size="mini" :step="1" ></el-input-number>
                </el-form-item>
                <el-form-item label="秒数止" required>
                  <el-input-number v-model="form2.maxSeconds" :min="form2.minSeconds + 1" size="mini" :max="60" :step="1"></el-input-number>
                </el-form-item>
                <el-form-item label="预约日期" required>
                  <el-date-picker v-model="form2.datatime" type="date" style="width:130px" :clearable="false" size="mini" value-format="yyyy-MM-dd" @change="v => {getDate(v, 2);}" :picker-options="pickerOptions"/>
                </el-form-item>
              </div>
            </el-form>
            <div class="df" style="height:35px;margin-top:10px;">
              <a href="https://api.boss.i-town.cn/api/SmallUserArchives/DownLoadUserTemplate" class="ml10">下载人员信息模板</a>
              <el-button type="success" size="small" class="ml10" @click="userAdd">人员添加</el-button>
              <!-- <el-button type="success" size="small" class="ml10" @click="downloadExcel">下载人员信息模板</el-button> -->
              <div style="width: 120px" v-show="url">
                <VolUploadFile :url="url" :upload-after="uploadAfter" class="ml10"></VolUploadFile>
              </div>
              <el-button type="success" size="small" class="ml10" @click="url = '/api/SmallUserArchives/Import'" v-show="!url">导入人员信息</el-button>
            </div>
          </div>
        </div>
        <el-table class="table" ref="goodsTableref2" :data="userList" tooltip-effect="dark" height="200" style="width: 100%;">
          <el-table-column label="序号" width="50px" align="center" type="index" />
          <el-table-column prop="name" label="游客姓名" width="85px" show-overflow-tooltip />
          <el-table-column prop="phone" label="手机号" show-overflow-tooltip />
          <el-table-column prop="id_card" label="身份证" show-overflow-tooltip />
          <el-table-column prop="title" label="商品名称" show-overflow-tooltip />
          <el-table-column prop="price" label="商品价格" width="85px" />
          <el-table-column prop="num" label="商品数量">
            <template slot-scope="scope">
              <el-input-number ref="refNumber" class="inpNum" controls-position="right" size="mini" :min="1" v-model="scope.row.num" />
            </template>
          </el-table-column>
          <el-table-column label="商品总价" width="85px">
            <template slot-scope="scope">
              {{ scope.row.num * scope.row.price }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="90px">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="editFun(scope.row, scope.$index)">修改</el-button>
              <el-button type="text" size="small" @click="deluser(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <div slot="footer" style="height:30px;">
        <Button type="success" @click="confirmFun(3)">保存任务</Button>
        <Button type="default" @click="confirmFun(2)">立即执行</Button>
      </div>
    </vol-box>
    <vol-box :lazy="true" :model.sync="model.box4" :title="index ? '编辑人员' : '新增人员'" :height="220" :width="400" :padding="20">
      <el-form :rules="rules" ref="ruleForm" :model="form" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" size="small" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" size="small" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="id_card">
          <el-input v-model="form.id_card" size="small" placeholder="请输入身份证号"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" style="height:30px;">
        <Button type="success" @click="onSubmit">确认</Button>
      </div>
    </vol-box>
    <vol-box :lazy="true" :model.sync="model.box5" title="任务信息" :height="300" :width="480" :padding="20">
      <el-form :rules="rules" ref="ruleForm3" :model="form3" label-width="80px">
        <el-form-item label="任务时间" prop="timeContainer">
          <el-date-picker v-model="form3.timeContainer" size="small" type="daterange" value-format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" placeholder="请选择任务时间" />
        </el-form-item>
        <!-- <el-form-item label="手机号" prop="phone">
          <el-input v-model="form3.phone" size="small" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input v-model="form3.stock" size="small" placeholder="请输入库存"></el-input>
        </el-form-item> -->
        <el-form-item label="备注">
          <el-input v-model="form3.remark" size="small" type="textarea" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" style="height:30px;">
        <Button type="success" @click="confirm3">确认保存任务</Button>
      </div>
    </vol-box>
  </div>
</template>
<script>
import VolBox from "@/components/basic/VolBox.vue";
import VolForm from "@/components/basic/VolForm.vue";
import VolUploadFile from "@/components/basic/VolUploadFile.vue";
export default {
  components: {
    VolForm,
    "vol-box": VolBox,
    VolUploadFile
  },
  watch: {},
  created() {},
  methods: {
    open() {
      this.model.box1 = true;
      // 清楚内容
      this.multipleList = [];
      this.goodTableData2 = [];
      this.userList = [];
      this.index = "";
      this.radioId = "";
      this.url = "";
      this.url2 = "";
      this.$nextTick(() => {
        this.$refs.formFieldsreset.reset();
        const scenic_poiId = this.getFormOption("scenic_poiId");
        scenic_poiId.data = [];
        this.goodTableData = []
      });
    },
    // 确认预约
    confirmFun(type) {
      if (this.goodTableData2.length == 0) {
        this.$Message.error("请先选择商品");
        return;
      }
      if (type == 1) {
        //预约
        this.confirm1();
      } else if (type == 2) {
        //批量预约
        this.confirm2();
      } else if (type == 3) {
        //保存任务
        if (!this.form2.datatime) {
          this.$Message.error("请先选择预约日期");
          return;
        }
        this.model.box5 = true;
        this.$nextTick(() => {
          this.$refs.ruleForm3.resetFields();
        });
      }
    },
    uploadFun() {
      if (!this.formFields.supplierCode) {
        this.$Message.error("请先选择采购供应商");
        return;
      } else if (!this.formFields.scenic_poiId) {
        this.$Message.error("请先选择景区");
        return;
      }
      this.url2 = "/api/Small_procure_order_item/Import";
    },
    confirm3() {
      //任务保存
      const params = {
        mainData: {
          scenic_name: this.formFields.scenic_name, //景区名字
          scenic_poiId: this.formFields.scenic_poiId,
          supplierCode: this.formFields.supplierCode,
          goods_id: this.goodTableData2[0].goods_id,
          remark: this.form3.remark,
          goods_name: this.goodTableData2[0].title,
          phone: this.form3.phone,
          stock: this.form3.stock,
          isdisable: 1,
          reservationTime: this.form2.datatime,
          minSeconds: this.form2.minSeconds,
          maxSeconds: this.form2.maxSeconds,
          startTime: this.form3.timeContainer[0],
          endTime: this.form3.timeContainer[1],
          merchantCode: "",
          merchantName: "",
          status: -1
        },
        detailData: null,
        delKeys: null
      };
      this.http.post("/api/Mall_procure_task/Add", params).then(res => {
        const obj = JSON.parse(res.data);
        if (this.userList.length && obj.data.id) {
          this.onSubfun3(obj.data.id);
        } else {
          this.model.box5 = false;
        }
      });
    },
    onSubfun3(id) {
      //任务保存人员信息
      const param = [];
      this.userList.forEach((_, i) => {
        param.push({
          touristname: _.name,
          phone: _.phone,
          id_card: _.id_card,
          num: _.num,
          taskid: id
        });
      });
      this.http.post("/api/Mall_procure_task_people/AddBatchPeople", param).then(res => {
        this.model.box5 = false;
      });
    },
    confirm1() {
      if (!this.formFileds2.datatime) {
        this.$Message.error("请先选择预约日期");
        return;
      }
      const param = [];
      this.goodTableData2.map(v => {
        param.push({
          ...v,
          name: this.formFileds2.name, //游客姓名
          phone: this.formFileds2.phone, //游客手机号
          id_card: this.formFileds2.id_card, //游客身份证
          playStartDate: this.formFileds2.datatime, //游客开始时间2024-03-11
          playEndDate: this.formFileds2.datatime, //游客开始时间2024-03-11
          maxSeconds: 0,
          minSeconds: 0,
          goodtype: 1,
          merchantCode: "",
          merchantName: "",
          status: -1,
          scenic_name: this.formFields.scenic_name, //景区名字
          scenic_poiId: this.formFields.scenic_poiId //景区ID
        });
      });
      this.onSubfun(param);
    },
    confirm2() {
      if (!this.form2.datatime) {
        this.$Message.error("请先选择预约日期");
        return;
      }
      if (this.userList.length == 0) {
        this.$Message.error("请填写人员信息");
        return;
      }
      if (this.form2.minSeconds >= this.form2.maxSeconds) {
        this.$Message.error("秒数止大于秒数起");
        return;
      }
      let param = [];
      // this.goodTableData2.map((v)=>{
      this.userList.map(_ => {
        param.push({
          // ...v,
          ..._,
          goodtype: 2,
          minSeconds: this.form2.minSeconds,
          maxSeconds: this.form2.maxSeconds,
          playStartDate: this.form2.datatime,
          playEndDate: this.form2.datatime,
          scenic_name: this.formFields.scenic_name, //景区名字
          scenic_poiId: this.formFields.scenic_poiId, //景区ID
          merchantCode: "",
          merchantName: "",
          status: -1
        });
      });
      // })
      this.onSubfun(param);
    },
    rowClickHandle(row) {
      this.radioId = row.goods_id;
      this.multipleList = [row];
    },
    onSubfun(param) {
      this.http.post("/api/Small_procure_order/AsyncSubmitProcureOrder", param).then(res => {
        if (res.status) {
          this.$message({ message: "操作成功", type: "success" });
        }
        for (let key in this.model) {
          this.model[key] = false;
        }
      });
    },
    // 添加人员弹窗
    userAdd() {
      this.model.box4 = true;
      this.index = false;
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields();
      });
    },
    // 编辑人员弹窗
    editFun(row, i) {
      this.index = i;
      this.form = JSON.parse(JSON.stringify(row));
      this.model.box4 = true;
    },
    // 删除人员
    deluser(i) {
      this.userList.splice(i, 1);
    },
    // 确认添加人员
    onSubmit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (this.index === false) {
            this.userList.push({ ...this.form, ...this.goodTableData2[0] });
          } else {
            this.$set(this.userList,this.index,JSON.parse(JSON.stringify(this.form)));
          }
          this.model.box4 = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    reservation(type) {
      if (this.multipleList.length == 0) {
        this.$Message.error("请先选择采购商品");
        return;
      }
      this.goodTableData2 = [];
      this.multipleList.map(row => {
        this.goodTableData2.push({
          title: row.name,
          num: 1,
          price: row.price,
          goods_id: row.goods_id,
          supplierProcureCode: this.formFields.supplierCode
        });
      });
      if (type == 1) {
        //预约
        this.model.box2 = true;
        this.$nextTick(() => {
          this.$refs.myform.reset();
        });
      } else {
        //批量预约
        this.model.box3 = true;
        this.form2 = {datatime: "",minSeconds: 1,maxSeconds: 2};
      }
    },
    getDate(val, type) {
      if (type == 1) {
        this.formFileds2.datatime = val;
      } else if (type == 2) {
        this.form2.datatime = val;
      }
      const ids = [];
      this.goodTableData2.forEach(v => {
        ids.push(v.goods_id);
      });
      this.http.post("/api/Mall_good/GetProcureGoodList", {...this.formFields, goods_id: ids.join(","),date: val}).then(res => {
        this.goodTableData2 = [];
        if (res.data) {
          res.data.forEach(row => {
            this.goodTableData2.push({
              title: row.name,
              num: 1,
              price: row.price,
              goods_id: row.goods_id,
              supplierProcureCode: this.formFields.supplierCode
            });
          });
          if (type == 2 && this.userList.length) {
            const a = [];
            this.userList.forEach(v => {
              this.goodTableData2.forEach(_ => {
                a.push({ ...v, ..._ });
              });
            });
            this.userList = a;
          }
        }
      });
    },
    getly(v) {
      this.formFields.supplierCode = v;
      if(!v){
        return
      }
      this.http.post("/api/Mall_procure_scenic/getPageData", 
      {order: "desc",page: 1,rows: 1000,sort: "id",
      wheres: `[{\"name\":\"scenic_supplierid\",\"value\":\"${v}\",\"displayType\":\"select\"}]`}).then(res => {
        const scenic_poiId = this.getFormOption("scenic_poiId");
        scenic_poiId.data = [];
        this.formFields.scenic_poiId = ''
        res.rows.map(v => {
          scenic_poiId.data.push({
            key: v.scenic_poiId,
            value: v.scenic_name
          });
        });
      });
    },
    getFormOption(field) {
      let option;
      this.formRules.forEach(x => {
        x.forEach(item => {
          if (item.field == field) {
            option = item;
          }
        });
      });
      return option;
    },
    changePoiId(v) {
      this.formFields.scenic_poiId = v;
      if(!v){
        return
      }
      const scenic_poiId = this.getFormOption("scenic_poiId");
      scenic_poiId.data.map(_ => {
        if (_.key == v) {
          return (this.formFields.scenic_name = _.value);
        }
      });
      this.changeCasc();
    },
    // 商品数据
    changeCasc() {
      this.http.post("/api/Mall_good/GetProcureGoods ", { ...this.formFields }).then(res => {
        this.goodTableData = res.data;
      });
    },
    //导入人员信息
    uploadAfter(result) {
      const param = {
        filepath: result.data,
        disCode: this.formFields.supplierCode
      };
      this.http.post("/api/Small_procure_order_item/ImportProcureSmallOrder", param).then(res => {
        if (res.data) {
          this.userList = [];
          res.data.forEach((_, i) => {
            this.userList.push({
              phone: _.phone,
              name: _.name,
              id_card: _.id_card,
              ...this.goodTableData2[0]
            });
          });
        }
        this.url = "";
        if (res.status) {
          this.$Message.success(res.message);
        } else {
          this.$Message.error(res.message);
        }
      });
      return true;
    },
    //导入 外部导入订单
    uploadAfter2(result) {
      const param = { filepath: result.data };
      this.http.post("/api/Small_procure_order_item/ImportProcureSmallOrder", param).then(res => {
        this.url2 = "";
        this.getDataList(res.data);
        if (res.status) {
          this.$Message.success(res.message);
        } else {
          this.$Message.error(res.message);
        }
      });
      return true;
    },
    getDataList(data) {
      if (!data || data.length == 0) {
        return;
      }
      const param = [];
      data.forEach(_ => {
        param.push({
          title: _.title, //商品名称
          num: _.num, //商品数量
          price: _.price, //商品价格
          goods_id: _.goods_id, //商品id
          name: _.name, //游客姓名
          phone: _.phone, //游客手机号
          id_card: _.id_card, //身份证
          playStartDate: _.playStartDate, //游戏开始时间2024-03-11
          playEndDate: _.playEndDate, //游戏开始时间2024-03-11
          ticketsCode: _.ticketsCode, //凭证码
          goodtype: 4, //订单类型1：手工预订，2：批量预订，3：自动预订,4:导入订单
          supplierProcureCode: this.formFields.supplierCode, //采购供应商id
          scenic_poiId: this.formFields.scenic_poiId, //景区id
          scenic_name: this.formFields.scenic_name, //景区名称
          merchantName: "",
          merchantCode: ""
        });
      });
      this.http.post("/api/Small_procure_order/ImportProcureOrder", param).then(res => {
        if (res.status) {
          this.$Message.success(res.message);
        } else {
          this.$Message.error(res.message);
        }
      });
    }
  },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          // 获取今天的日期
          const today = new Date();
          // 如果选择的日期在今天之后，则禁用
          return time.getTime() <= today.getTime();
        }
      },
      radioId: "",
      model: {
        box1: false,
        box2: false,
        box3: false,
        box4: false,
        box5: false
      },
      multipleList: [],
      goodTableData2: [],
      goodTableData: [],
      formFields: {
        supplierCode: "",
        scenic_poiId: "",
        scenic_name: ""
      },
      formRules: [
        [
          {
            title: "采购供应商",
            field: "supplierCode",
            type: "select",
            dataKey: "procurementsupplier",
            data: [],
            clearable:false,
            required: true,
            onChange: val => {
              this.getly(val);
            }
          },
          {
            title: "景区",
            field: "scenic_poiId",
            type: "select",
            data: [],
            clearable:false,
            required: true,
            onChange: val => {
              this.changePoiId(val);
            }
          }
        ]
      ],
      formFileds2: {
        name: "",
        phone: "",
        datatime: "",
        id_card: ""
      },
      formRules2: [
        [
          {
            title: "预约日期",
            field: "datatime",
            type: "date1",
            clearable: false,
            min: new Date().getTime(),
            required: true,
            onChange: val => {
              this.getDate(val, 1);
            }
          },
          { title: "姓名", field: "name", type: "text" }
        ],
        [
          { title: "手机号", field: "phone", type: "phone" },
          { title: "身份证号", field: "id_card", type: "text" }
        ]
      ],
      form: {
        name: "",
        phone: "",
        id_card: ""
      },
      rules: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
        id_card: [
          { required: true, message: "请输入身份证号", trigger: "blur" }
        ]
      },
      index: "",
      userList: [],
      url: "",
      url2: "",
      form2: {
        datatime: "",
        maxSeconds: "",
        minSeconds: 1
      },
      form3: {
        phone: "",
        remark: "",
        stock: "",
        timeContainer: []
      }
    };
  }
};
</script>
<style scoped>
.df {
  display: flex;
}
.clearfix {
  justify-content: space-between;
  height: 35px;
  line-height: 35px;
  overflow: hidden;
}
.ml10 {
  margin-left: 10px;
}
.inpNum {
  width: 100px !important;
}
</style>
